﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Coder
{
    /// <summary>
    /// 配置集合
    /// </summary>
    public class Configures : Dictionary<string, string>
    {

        public Configures() { }

        /// <summary>
        /// 检测约束
        /// </summary>
        public void CheckConstraints(string[] keys)
        {
            foreach (var key in keys)
            {
                if (!base.ContainsKey(key)) throw new Exception($"缺少'{key}'配置");
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public void SetConfigureStrings(string[] configs)
        {
            if (configs == null) return;
            // 遍历所有的参数
            for (int i = 0; i < configs.Length; i++)
            {
                this.SetConfigureString(configs[i]);
            }
        }

        /// <summary>
        /// 设置配置项
        /// 格式为 -key:"value"
        /// </summary>
        /// <param name="config"></param>
        public void SetConfigureString(string config)
        {
            if (string.IsNullOrEmpty(config)) throw new Exception("缺少配置项");
            Console.WriteLine($"[Configure] {config}");
            if (config.Length < 3) throw new Exception($"不支持的配置语句'{config}'");
            if (!config.StartsWith("--")) throw new Exception($"不支持的配置语句'{config}'");
            int idx = config.IndexOf(':');
            // 不存在冒号
            if (idx < 0)
            {
                string k = config.Substring(2);
                if (string.IsNullOrEmpty(k)) throw new Exception("配置键不能为空");
                if (k[0] != '@') k = k.ToLower(); // @开头不处理，不然进行小写处理
                base[k] = "";
                return;
            }
            string key = config.Substring(2, idx - 2);
            if (string.IsNullOrEmpty(key)) throw new Exception("配置键不能为空");
            if (key[0] != '@') key = key.ToLower(); // @开头不处理，不然进行小写处理
            string value = config.Substring(idx + 1);
            if (value.Length > 1)
            {
                if (value.StartsWith("\"") && value.EndsWith("\"")) value = value.Substring(1, value.Length - 2);
            }
            base[key] = value;
        }
    }
}
